<?php

namespace backend\controllers;

use backend\controllers\RbacController;
use backend\models\TbaMemberinfo;
use backend\models\TbaMembeaddrinfo;
use frontend\models\UserForm;
use yii\base\Exception;
use backend\models\TbaMemberinforecordinfo;
use backend\models\TmeOrderinfo;
/**
 * #name=会员管理#
 * 
 */
class MembermanageController extends RbacController {
	public $layout='ace';//使用ace布局
	
	/**
	 * #operation=数据表展现#
	 */
	public function actionShow(){
		$tableid=0;
		return $this->render('index',['tableid'=>$tableid]);
	}

	/**
	 * #operation=异步查询用户数据#
	 * 
	 */
	public function actionData(){
		
		$start=\Yii::$app->request->post('start');//开始条数
		$length=\Yii::$app->request->post('length');//长度
		$draw=\Yii::$app->request->post('draw');//当前页
		$column=\Yii::$app->request->post('order')[0]['column'];//排序字段
		$dir=\Yii::$app->request->post('order')[0]['dir'];//排序方式
		$columnNameArray=[
			'1'=>'username',
			'4'=>'Balance',
			'5'=>'RegDate'
		];
		$columnName=$columnNameArray[$column];
		//搜索条件
		if(!empty(\Yii::$app->request->post('search')['value'])){
			$search=\Yii::$app->request->post('search')['value'];
			$where="username like '%".$search."%'";
		}else{
			$where="";
		}
		//查询所有用户的信息
		$user=TbaMemberinfo::find()->where($where)->orderBy($columnName." ".$dir)->limit($length)->offset($start)->asArray()->all();
		//查询用户总个数
		$count=TbaMemberinfo::find()->count();
		$data=[];
		foreach($user as $u){
			$dataArray=[];
			$dataArray['check']='<center><label class="pos-rel"><input type="checkbox" class="ace" /><span class="lbl"></span></label></center>';
			$dataArray['username']=$u['username'];
			$dataArray['Email']=$u['Email'];
			$dataArray['lName']=$u['lName'];
			$dataArray['Balance']=$u['Balance'];
			$dataArray['RegDate']=$u['RegDate'];
			$dataArray['options']="<div class=\"hidden-sm hidden-xs action-buttons\">
				<a class=\"blue\" onclick=\"see(".$u['ID'].")\">
					<i class=\"ace-icon fa fa-search-plus bigger-130\"></i>
				</a>

				<a class=\"green\" onclick=\"update(".$u['ID'].")\">
					<i class=\"ace-icon fa fa-pencil bigger-130\"></i>
				</a>

				<a class=\"red\"  onclick=\"javascript:return show_confirm(".$u['ID'].")\">
					<i class=\"ace-icon fa fa-trash-o bigger-130\"></i>
				</a>
			</div>";
			$data[]=$dataArray;
		}
		$temp=[
			'draw'=>$draw,
			'recordsTotal'=>$count,
			'recordsFiltered'=>$count,
			'data'=>$data
		];
		return json_encode($temp);
		
	}
	/**
	 * #operation=添加会员#
	 */
	public function actionAddmember(){
		//实例化用户表单模型，赋予场景
		$model=new UserForm(['scenario'=>'register']);
		//判断是否有提交动作
		if(\Yii::$app->request->isPost){
			$model->attributes=\Yii::$app->request->post('UserForm');
			//进行表单验证
			if($model->validate()){
				//进行数据写入
				$user=new TbaMemberinfo();
				$user->username=$model->username;
				$user->auth_key=\Yii::$app->security->generateRandomString();
				$user->Pwd=substr(md5(trim($model->Pwd.$user->auth_key)), 9,12);//密码通过md5加密后去第九位后边的12个字符
				$user->Email=$model->Email;
				$user->lName=$model->lName;
				$user->Remark=$model->Remark;
				if($user->save()){
					//跳转页面
					$this->redirect(['membermanage/addmember']);
				}else{	
					var_dump($user->errors);exit;
					throw new \Exception('数据写入失败', '404');
				}
			}else{
				$tableid=1;
				return $this->render('index',['model'=>$model,'tableid'=>$tableid]);
			}
		}
		$tableid=0;
		return $this->render('index',['model'=>$model,'tableid'=>$tableid]);
	}		
	/**
	 * #operation=查看会员详情#
	 * 
	 * 
	 */
	public function actionMempreview(){
		
		 if( \Yii::$app->request->post('action') == "query_action"){
		 	$id=\Yii::$app->request->post('id');
			$memadd=TbaMembeaddrinfo::findOne(['TBa_ID'=>$id]);
			if($memadd){
				echo "<div class=\"form-group field-userform-username\"\">";
				echo "<label class=\"col-sm-3 control-label no-padding-right\">会员名：</label>
						<input type=\"text\" value=\"".$memadd->username."\" disabled=\"disabled\" style=\"width:200px;\" /><br /><br />";
				echo "<label class=\"col-sm-3 control-label no-padding-right\">收货人：</label>
						<input type=\"text\" value=\"".$memadd->RecMan."\" disabled=\"disabled\" style=\"width:200px;\" /><br /><br />";
				echo "<label class=\"col-sm-3 control-label no-padding-right\">联系电话：</label>
						<input type=\"text\" value=\"".$memadd->Tel."\" disabled=\"disabled\" style=\"width:200px;\" /><br /><br />";
				echo "<label class=\"col-sm-3 control-label no-padding-right\">收货地址：</label>
						<input type=\"text\" value=\"".$memadd->RecAddress."\" disabled=\"disabled\" style=\"width:200px;\" /><br /><br />";
				echo "<label class=\"col-sm-3 control-label no-padding-right\">邮政编码：</label>
						<input type=\"text\" value=\"".$memadd->PostCode."\" disabled=\"disabled\" style=\"width:200px;\" /><br /><br />";
				echo "</div>";
			}else{
				echo "<h4 class=\"pink\">
						<i class=\"ace-icon fa fa-hand-o-right icon-animated-hand-pointer blue\"></i>
						未填写收货信息
					</h4>";						
			}
			
		} 
		
	}
	/**
	 * #operation=修改会员信息#
	 * 
	 */
	public function actionMemupdate(){
		if(\Yii::$app->request->post('action')=='update_action'){
			$memform=new UserForm();
			$memform->scenario='update';
			$id=\Yii::$app->request->post('id');
			\Yii::$app->session->set('memid',$id);//传递要修改的用户id
			$membermsg=TbaMemberinfo::findOne(['ID'=>$id]);
			if($membermsg){
				return $this->renderPartial('memupdate',[
					'model'=>$memform,
					'id'=>$id,
					'username'=>$membermsg->username,
					'password'=>$membermsg->Pwd,
					'email'=>$membermsg->Email,
					'lname'=>$membermsg->lName,
				]);
			}
		}
		//提交表单后进行数据修改
		if(\Yii::$app->request->isPost){
			$submitform=new UserForm();
			$submitform->scenario='update';
			$submitform->attributes=\Yii::$app->request->post('UserForm');
			if($submitform->validate()){
				$memid=\Yii::$app->session->get('memid');
				$updatemem=TbaMemberinfo::findOne(['ID'=>$memid]);
				$updatemem->Pwd=substr(md5(trim($submitform->Pwd.$updatemem->auth_key)), 9,12);
				$updatemem->Email=$submitform->Email;
				$updatemem->lName=$submitform->lName;
				
				if($updatemem->save()){
					$this->redirect(['membermanage/addmember']);
				}else{
					throw new Exception('数据写入失败', '404');
				} 
			}else{				
				$key=array_keys($submitform->errors);
				foreach ($key as $k){
					exit("<script>alert(\"".$submitform->errors[$k][0]."\");window.history.go(-1);</script>");
				}
			}
			
		}				
	}
	/**
	 * #operation=删除会员#
	 */
	public function actionDelete(){
		$id=\Yii::$app->request->post('id');
		$connection=\Yii::$app->db;					//建立数据库连接
		$transaction=$connection->beginTransaction();//开启事务
		//查询要删除用户的用户表信息
		$delmem=TbaMemberinfo::findOne(['ID'=>$id]);
		if($delmem->Balance != 0){
			exit('该用户有余额，不能进行删除');
		}	
		//进行条件判断 如果会员有订单信息就不进行删除会员操作
		$memberorderid=TmeOrderinfo::find()->where(['Uid'=>$id]);		
		$counts=$memberorderid->count();
		if($counts!=0){
			echo "不能进行删除！";
			exit;
		}
			try {			
				//查询该用户是否存在收货地址信息，如果存在进行删除
				$memadd=TbaMembeaddrinfo::find()->where(['Tba_ID'=>$id]);
				$memaddcount=$memadd->count();//统计查询个数
				if($memaddcount !=0){
			
					if(TbaMembeaddrinfo::deleteAll(['Tba_ID'=>$id])==0){
							
						throw new Exception('用户地址删除失败',1);
					}else{
						TbaMembeaddrinfo::deleteAll(['Tba_ID'=>$id]);
					}
				}
				//查询该用户是否存在充值记录信息，如果存在进行删除
				$memrecharge=TbaMemberinforecordinfo::find()->where(['ID'=>$id]);
				$memrechargecount=$memrecharge->count();//统计查询个数
				if($memrechargecount != 0){
			
					if(TbaMemberinforecordinfo::deleteAll(['ID'=>$id])==0){
						throw new Exception('充值信息数据删除失败',2);
					}else{
						TbaMemberinforecordinfo::deleteAll(['ID'=>$id]);
					}
				}
				//进行会员表信息删除
				if($delmem->delete() !=0){
					$delmem->delete();
					$this->redirect(['membermanage/addmember']);
				}else{
					throw new Exception('用户表数据删除失败', 4);
				}
				$transaction->commit();//提交事务
			} catch (Exception $e) {
				
				//echo "错误信息为:".$e->getMessage();
				$transaction->rollBack();//事务回滚
			}
		
		
	}
	
}

?>